package com.relax.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.relax.order.dto.Order;
import com.relax.order.feign.OrderFeign;
import com.relax.pay.dto.PayOrder;
import com.relax.service.OrderPayService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderPayServiceImpl implements OrderPayService {


    public OrderPayServiceImpl() {
        System.out.println("OrderPayServiceImpl");
    }

    @Autowired
    private OrderFeign orderFeign;

    public void setOrderFeign(OrderFeign orderFeign) {
        this.orderFeign = orderFeign;
    }

    //    @Autowired
//    private PayFeign payFeign;


    @Override
    public PayOrder orderPay(Integer userId) {
        Order order = orderFeign.create(userId);
        PayOrder payOrder = new PayOrder();
        BeanUtils.copyProperties(order, payOrder);
//        return payFeign.orderPay(payOrder);
        return payOrder;

    }

    @Override
    public String sentinelTest(Integer userId,Integer sleepTime) {
        Entry entry = null;
        try {
            entry = SphU.entry("sentinelTest");
            // 被保护的逻辑
             doSomething(sleepTime);
            return userId + "";
        } catch (BlockException ex) {
            // 处理被流控的逻辑
            System.out.println("请求被sentinel 阻塞中blocked!");
            return "请求被sentinel 阻塞中blocked!";
        } finally {
            if (null!= entry){
                entry.close();
            }

        }
    }

    private void doSomething(Integer sleepTime)   {
        if(null != sleepTime){
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
